<template>
  <div>
    <div class="file-uploader">
      <!-- 文件选择区域 -->
      <div class="upload-area" @click="triggerFileInput">
        <input
          type="file"
          ref="fileInput"
          multiple
          :accept="accept"
          @change="handleFileSelect"
          style="display: none"
        />
        <div class="upload-prompt">
          <i class="upload-icon">📁</i>
          <p>点击或拖拽文件到此处上传</p>
          <p class="hint">(最多 {{ maxFiles }} 个文件)</p>
        </div>
      </div>

      <!-- 文件列表 -->
      <div class="file-list">
        <div v-for="file in fileList" :key="file.id" class="file-item">
          <div class="file-info">
            <span class="file-name" :title="file.name">{{ truncateFileName(file.name) }}</span>
            <span class="file-size">{{ formatFileSize(file.size) }}</span>
          </div>

          <!-- 上传进度 -->
          <div class="progress-container">
            <div class="progress-bar" :style="{ width: file.progress + '%' }"></div>
            <span class="progress-text">{{ file.progress }}%</span>
          </div>

          <!-- 操作按钮 -->
          <div class="file-actions">
            <button
              v-if="file.status === 'uploading'"
              @click="cancelUpload(file)"
              class="cancel-btn"
            >
              取消
            </button>
            <button v-if="file.status !== 'uploading'" @click="removeFile(file)" class="remove-btn">
              移除
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getUserInfo } from "@/service/api/user";

const handleUserInfo = () => {
  const params = { page: 1, limit: 10 };
  getUserInfo(params).then(res => {
    console.log(res);
  });
};
handleUserInfo();

// import { defineComponent, ref, reactive } from 'vue';
import axios, { type AxiosRequestConfig, type CancelTokenSource } from "axios";

const props = defineProps({
  // 上传API地址
  uploadUrl: {
    type: String,
    required: true,
  },
  // 最大文件数量
  maxFiles: {
    type: Number,
    default: 20,
  },
  // 接受的文件类型
  accept: {
    type: String,
    default: "*/*",
  },
});

interface UploadFile {
  id: string;
  file: File;
  name: string;
  size: number;
  progress: number;
  status: "waiting" | "uploading" | "success" | "error" | "canceled";
  cancelTokenSource?: CancelTokenSource;
}

const fileInput = ref<HTMLInputElement | null>(null);
const fileList = ref<UploadFile[]>([]);

// 触发文件选择
const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click();
  }
};

// 处理文件选择
const handleFileSelect = (e: Event) => {
  const input = e.target as HTMLInputElement;
  const files = input.files;

  if (!files || files.length === 0) return;

  // 检查文件数量限制
  const remainingSlots = props.maxFiles - fileList.value.length;
  if (remainingSlots <= 0) {
    alert(`最多只能上传 ${props.maxFiles} 个文件`);
    return;
  }

  // 添加新文件到列表
  const filesToAdd = Array.from(files).slice(0, remainingSlots);
  filesToAdd.forEach(file => {
    const fileItem: UploadFile = {
      id: generateFileId(file),
      file,
      name: file.name,
      size: file.size,
      progress: 0,
      status: "waiting",
    };
    fileList.value.push(fileItem);

    // 开始上传
    startUpload(fileItem);
  });

  // 重置input
  if (fileInput.value) {
    fileInput.value.value = "";
  }
};

// 生成文件唯一ID
const generateFileId = (file: File): string => {
  return `${file.name}-${file.size}-${Date.now()}`;
};

// 开始上传文件
const startUpload = async (fileItem: UploadFile) => {
  const formData = new FormData();
  formData.append("file", fileItem.file);

  // 创建取消令牌
  const cancelTokenSource = axios.CancelToken.source();
  fileItem.cancelTokenSource = cancelTokenSource;
  fileItem.status = "uploading";

  try {
    const config: AxiosRequestConfig = {
      headers: { "Content-Type": "multipart/form-data" },
      onUploadProgress: progressEvent => {
        if (progressEvent.total) {
          const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
          fileItem.progress = percent;
        }
      },
      cancelToken: cancelTokenSource.token,
    };

    await axios.post(props.uploadUrl, formData, config);
    fileItem.status = "success";
  } catch (error) {
    if (axios.isCancel(error)) {
      fileItem.status = "canceled";
    } else {
      console.error("上传失败:", error);
      fileItem.status = "error";
    }
  } finally {
    delete fileItem.cancelTokenSource;
  }
};

// 取消上传
const cancelUpload = (fileItem: UploadFile) => {
  if (fileItem.cancelTokenSource) {
    fileItem.cancelTokenSource.cancel("用户取消上传");
  }
};

// 移除文件
const removeFile = (fileItem: UploadFile) => {
  fileList.value = fileList.value.filter(file => file.id !== fileItem.id);

  // 如果文件正在上传，先取消
  if (fileItem.status === "uploading" && fileItem.cancelTokenSource) {
    fileItem.cancelTokenSource.cancel();
  }
};

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const sizes = ["Bytes", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};

// 截断文件名
const truncateFileName = (name: string, maxLength = 30): string => {
  if (name.length <= maxLength) return name;
  const extension = name.split(".").pop();
  const baseName = name.substring(0, maxLength - (extension ? extension.length + 4 : 3));
  return `${baseName}...${extension ? "." + extension : ""}`;
};
</script>

<style lang="less" scoped>
.file-uploader {
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  max-width: 600px;
  margin: 0 auto;
}

.upload-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 2rem;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
  background-color: #f9f9f9;
}

.upload-area:hover {
  border-color: #409eff;
  background-color: #f0f7ff;
}

.upload-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
  display: block;
}

.hint {
  color: #999;
  font-size: 0.9rem;
  margin-top: 0.5rem;
}

.file-list {
  margin-top: 1.5rem;
}

.file-item {
  border: 1px solid #eee;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 12px;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.file-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.file-name {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight: 500;
}

.file-size {
  color: #666;
  margin-left: 10px;
  font-size: 0.9rem;
}

.progress-container {
  height: 24px;
  background-color: #e9ecef;
  border-radius: 4px;
  margin-bottom: 8px;
  position: relative;
  overflow: hidden;
}

.progress-bar {
  height: 100%;
  background-color: #409eff;
  transition: width 0.3s ease;
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  font-size: 0.8rem;
  font-weight: bold;
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
}

.file-actions {
  text-align: right;
}

.cancel-btn,
.remove-btn {
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.2s;
}

.cancel-btn {
  background-color: #ff4d4f;
  color: white;
}

.cancel-btn:hover {
  background-color: #ff7875;
}

.remove-btn {
  background-color: #f5f5f5;
  color: #666;
}

.remove-btn:hover {
  background-color: #e5e5e5;
}
</style>
